package com.xl.sharedModel;

import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;

/**
 * JdkVersion: 1.8
 * Author: lei·xie
 * Created: 2024/8/7 0007 10:44
 * Description: 共享模型 线程安全分析
 */
@Slf4j(topic = "c.Test5")
public class Test05 {

    static final int THREAD_NUMBER = 2;
    static final int LOOP_NUMBER = 200;
    public static void main(String[] args) throws InterruptedException {
        ThreadSafeSubClass threadSafe = new ThreadSafeSubClass();
        for (int i = 0; i < THREAD_NUMBER; i++) {
            new Thread(() -> threadSafe.method1(LOOP_NUMBER),"Thread"+(i+1)).start();
        }
    }
}

/*class ThreadUnSafe {

    ArrayList<String> list = new ArrayList<>();
    public void method1(int loopNumber) {
        for (int i=0; i<loopNumber; i++) {
            method2();
            method3();
        }
    }

    public void method2() {
        list.add("1");
    }
    public void method3() {
        list.remove(0);
    }
}*/

/*
class ThreadSafe {

    public void method1(int loopNumber) {
        ArrayList<String> list = new ArrayList<>();
        for (int i=0; i<loopNumber; i++) {
            method2(list);
            method3(list);
        }
    }

    private void method2(ArrayList<String> list) {
        list.add("1");
    }
    private void method3(ArrayList<String> list) {
        list.remove(0);
    }
}*/

/*
class ThreadSafe {

    public void method1(int loopNumber) {
        ArrayList<String> list = new ArrayList<>();
        for (int i=0; i<loopNumber; i++) {
            method2(list);
            method3(list);
        }
    }

    public void method2(ArrayList<String> list) {
        list.add("1");
    }
    public void method3(ArrayList<String> list) {
        list.remove(0);
    }
}*/

class ThreadSafe {

    public void method1(int loopNumber) {
        ArrayList<String> list = new ArrayList<>();
        for (int i=0; i<loopNumber; i++) {
            method2(list);
            method3(list);
        }
    }

    public void method2(ArrayList<String> list) {
        list.add("1");
    }
    public void method3(ArrayList<String> list) {
        list.remove(0);
    }
}

class ThreadSafeSubClass extends ThreadSafe {
    @Override
    public void method3(ArrayList<String> list) {
        new Thread(() -> list.remove(0)).start();
    }
}